﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;

namespace TwoPageView3 {
    public partial class MainWindow : Window, IFolderTreeViewEvent {
        private TilePanelControl mTilePanelControl;
        private CancellationTokenSource mCts;
        private Task mImageDisplayTask;

        private void InitializeTreeThumbBrowse() {
            ResizePanelToFillParent(mTreeThumbBrowserGrid);
        }

        private void UpdateViewsTreeThumbBrowse() {
            mState = State.TreeThumbBrowse;

            mTreeThumbBrowserGrid.Visibility = Visibility.Visible;
            mCloseupViewGrid.Visibility      = Visibility.Collapsed;
        }

        private void SetupTreeThumbBrowse() {
            mFolderTreeView.ConnectTo(this);
            mTilePanelControl = new TilePanelControl(mPanel, mUserPreference, OnTileItemClicked);
            mTilePanelControl.ConnectTo(mThumbnailCache);
            mTilePanelControl.UpdateFlowDirection(FlowDirection.RightToLeft);


            //mFolderTreeViewControl.SelectFolder(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
        }

        /// <summary>
        /// this method is not reentrant
        /// </summary>
        void IFolderTreeViewEvent.OnFolderTreeViewSelected(ITpvDirectoryInfo di) {
            CancelAndWaitUntilImageDisplayTaskEnds();

            ShowImagesInDirectory(di);
        }

        private void CancelAndWaitUntilImageDisplayTaskEnds() {
            if (mCts != null && mImageDisplayTask != null) {
                mCts.Cancel();
                mImageDisplayTask.Wait();

                mCts = null;
                mImageDisplayTask = null;
            }
        }

        private void ShowImagesInDirectory(ITpvDirectoryInfo di) {
            mCts = new CancellationTokenSource();
            var token = mCts.Token;

            mTilePanelControl.ClearAllItems();

            var uiThreadDispatcher = Dispatcher.CurrentDispatcher;

            mImageDisplayTask = Task.Factory.StartNew(new Action(() => {
                if (token.IsCancellationRequested) {
                    Console.WriteLine("  Canceled 1 on startup");
                    return;
                }

                var fileEnum = di.EnumerateImageFiles();
                if (null == fileEnum) {
                    return;
                }

                if (token.IsCancellationRequested) {
                    Console.WriteLine("  Canceled 2 after enumerateImageFiles");
                    return;
                }

                try {
                    foreach (var c in fileEnum) {
                        if (token.IsCancellationRequested) {
                            Console.WriteLine("  Canceled 3 {0}", c.DisplayPath);
                            return;
                        }
                        uiThreadDispatcher.Invoke(new Action(() => {
                            mTilePanelControl.Add(c, token);
                            mTilePanelControl.UpdateItemPosition();
                        }), DispatcherPriority.Render, token);
                    }
                } catch (TaskCanceledException ex) {
                    Console.WriteLine("task canceled {0}", ex);
                }

            }), token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }

        void OnTileItemClicked(TiledImageItem item) {
            UpdateViewsCloseupView();

            var di = mFolderTreeView.SelectedDirectoryInfo();
            var fileEnum = di.EnumerateImageFiles();
            mFileEnumerator = fileEnum.GetEnumerator();
            mCloseupFileList.Clear();            

            ShowCloseupView(item.OrdinalOnDirectory, ShowCommand.SpecifiedPage);
        }

        void OnKeyUpOnTreeThumbBrowser(KeyEventArgs e) {
        }
    }
}
